let Promise = require('bluebird');
let request = Promise.promisify(require('request'));
let fs = require('fs');
let util = require('../libs/util');
let preFix = 'https://api.weixin.qq.com/cgi-bin';
let api = {
    accessToken: preFix + '/token?grant_type=client_credential',
    upload: preFix + '/media/upload?'
}

function Wechat(opt) {
    var that = this;
    this.appID = opt.appID;
    this.appsecret = opt.appsecret;
    this.getAccessToken = opt.getAccessToken;
    this.saveAccessToken = opt.saveAccessToken;
    this.fetchAccessToken();
    
}

//验证票据（access_token）有效性
Wechat.prototype.isValidAccessToken = function(data) {
    if(!data || !data.access_token || !data.expires_in) {
        return false;
    }
    var access_token = data.access_token;
    var expires_in = data.expires_in;
    var now = new Date().getTime();

    if(now < expires_in) {
        return true;
    }else {
        return false;
    }
}

//更新票据
Wechat.prototype.updateAccessToken = function() {
    let appID = this.appID;
    let appsecret = this.appsecret;
    let url = api.accessToken + '&appid=' + appID + '&secret=' + appsecret
    return new Promise((resolve,reject) => {
        request({url: url,json: true}).then((response) => {
            let data = response.body;
            let now = new Date().getTime();
            let expires_in = (data.expires_in - 20) * 1000 + now;
            data.expires_in = expires_in;
            resolve(data);
        })
    })
    
}

//获取票据
Wechat.prototype.fetchAccessToken = function() {
    let that = this;
    if(this.access_token && this.expires_in) {
        if(this.isValidAccessToken(this)) {
            return Promise.resolve(this)
        }
    }
    this.getAccessToken().then(data => {
        try {
            data = JSON.parse(data);
        }catch(e) {
            return that.updateAccessToken();
        }
        if(that.isValidAccessToken(data)) {
            return Promise.resolve(data);
        }else {
            return that.updateAccessToken();
        }
    }).then(data => {
        that.access_token = data.access_token;
        that.expires_in = data.expires_in;
        that.saveAccessToken(data);
        return Promise.resolve(data);
    })
}

//上传素材
Wechat.prototype.uploadMaterial = function(type,filepath) {
    let that = this;
    let form = {
        media: fs.createReadStream(filepath)
    }
    return new Promise((resolve,reject) => {
        that.fetchAccessToken().then(data => {
            let url = api.upload + 'access_token=' + data.access_token + '&type=' + type
            request({method: 'POST',url: url,formData: form,json: true}).then((response) => {
                let _data = response.body;
                if(_data) resolve(_data);
                else {
                    throw new Error('uplaod faild')
                }
                
            }).catch(err => {
                reject(err);
            })
        })

    })
    
}

//回复
Wechat.prototype.reply = function() {
    let content = this.body;
    let message = this.weixin;
    let xml = util.tpl(content,message)
    console.log(xml);
    this.status = 200;
    this.type = 'application/xml';
    this.body = xml;
}

module.exports = Wechat